package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.beans.UserInfoBean;
import com.hxkcloud.patient.beans.UserMsgBean;
import com.hxkcloud.patient.interfaces.IResponseNewMsgInfoListener;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BadgeUtil;
import com.hxkcloud.patient.utils.SharedPreferenceUtil;
import com.hxkcloud.patient.utils.StringUtil;

import java.util.List;

/**
 * Created by william_sun on 2016-07-18.
 * Description:消息主页，护士有检测题型、评估提醒、系统消息、最新消息，患者有所有联系人、评估提醒、医生评价、系统消息、最新消息
 */
public class MessageMainActivity extends BaseFragmentActivity implements View.OnClickListener {
    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;

    private AppBarLayout appbar;
    private LinearLayout ll_allcontacts;
    private ImageView iv_allcontacts;
    private LinearLayout ll_monitor;
    private ImageView iv_monitor;
    private ImageView iv_monitorp;
    private LinearLayout ll_assess;
    private ImageView iv_assess;
    private ImageView iv_assessp;
    private LinearLayout ll_evalution;
    private ImageView iv_evalution;
    private ImageView iv_evalutionp;
    private LinearLayout ll_system;
    private ImageView iv_system;
    private ImageView iv_systemp;

    private LinearLayout ll_users;

//    private PullToRefreshLayout refreshLayout;
//    private PullableRecyclerView recycleView;

//    private ArrayList<MessageBean> msgs;
//    private MsgMainAdapter adapter;

    private EaseConversationListFragment conversationListFragment;

    private EMMessageListener msgListener;

    private List<UserInfoBean> users;//用户信息

    public static MessageMainActivity messageMainActivity;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_GETUSERINFO_SUCCESS:
                if (conversationListFragment != null) {
                    users = ((List<UserInfoBean>) msg.obj);
                    if (users != null && users.size() > 0) {
                        String[] headImgs = new String[users.size()];
                        String[] tels = new String[users.size()];
                        String[] names = new String[users.size()];
                        for (int i = 0; i < users.size(); i++) {
                            UserInfoBean user = users.get(i);
                            headImgs[i] = user.getHeadImg();
                            tels[i] = user.getTel();
                            names[i] = user.getName();
                        }
                        conversationListFragment.setUserInfo(headImgs, tels, names, loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient) ? 0 : 1);
                    }
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_messagemain);

//        EaseUI.getInstance().init(this, null);
        initView();
        initListener();
        initData();

        messageMainActivity = this;
    }

    private void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);

        appbar = (AppBarLayout) findViewById(R.id.appbar_messagemain);
        ll_allcontacts = (LinearLayout) findViewById(R.id.ll_messagemain_allcontacts);
        iv_allcontacts = (ImageView) findViewById(R.id.iv_messagemain_allcontacts);
        ll_monitor = (LinearLayout) findViewById(R.id.ll_messagemain_monitor);
        iv_monitor = (ImageView) findViewById(R.id.iv_messagemain_monitor);
        iv_monitorp = (ImageView) findViewById(R.id.iv_msgmonitor_remindpoint);
        ll_assess = (LinearLayout) findViewById(R.id.ll_messagemain_assess);
        iv_assess = (ImageView) findViewById(R.id.iv_messagemain_assess);
        iv_assessp = (ImageView) findViewById(R.id.iv_msgassess_remindpoint);
        ll_evalution = (LinearLayout) findViewById(R.id.ll_messagemain_evalution);
        iv_evalution = (ImageView) findViewById(R.id.iv_messagemain_evalution);
        iv_evalutionp = (ImageView) findViewById(R.id.iv_msgassess_evalutionpoint);
        ll_system = (LinearLayout) findViewById(R.id.ll_messagemain_system);
        iv_system = (ImageView) findViewById(R.id.iv_messagemain_system);
        iv_systemp = (ImageView) findViewById(R.id.iv_msgsystem_remindpoint);
        ll_users = (LinearLayout) findViewById(R.id.ll_messageMain_users);

//        refreshLayout = (PullToRefreshLayout) findViewById(R.id.refreshlayout_messagemain);
//        recycleView = (PullableRecyclerView) findViewById(R.id.recyclerview_messagemain);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText(getResources().getText(R.string.message));
        iv_back.setOnClickListener(this);

        RelativeLayout.LayoutParams lp_iv = new RelativeLayout.LayoutParams(screenWidth / 8, screenWidth / 8);
        iv_allcontacts.setLayoutParams(lp_iv);
        iv_monitor.setLayoutParams(lp_iv);
        iv_assess.setLayoutParams(lp_iv);
        iv_evalution.setLayoutParams(lp_iv);
        iv_system.setLayoutParams(lp_iv);

        ll_allcontacts.setOnClickListener(this);
        ll_monitor.setOnClickListener(this);
        ll_assess.setOnClickListener(this);
        ll_evalution.setOnClickListener(this);
        ll_system.setOnClickListener(this);

        if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) {//patient
            ll_monitor.setVisibility(View.GONE);
            ll_evalution.setVisibility(View.VISIBLE);
        }
        if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_nurse)) {//nurse
            ll_allcontacts.setVisibility(View.GONE);
        }

        msgListener = new EMMessageListener() {

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                //收到消息
                System.out.println("onMessageReceived " + messages.size() + messages.get(0).getFrom());
                conversationListFragment.refresh();
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息
                System.out.println("onCmdMessageReceived " + messages.size());
            }

            @Override
            public void onMessageReadAckReceived(List<EMMessage> messages) {
                //收到已读回执
                System.out.println("onMessageReadAckReceived " + messages.size());
            }

            @Override
            public void onMessageDeliveryAckReceived(List<EMMessage> message) {
                //收到已送达回执
                System.out.println("onMessageDeliveryAckReceived " + message.size());
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
                System.out.println("onMessageChanged " + message.getUserName());
            }
        };
        EMClient.getInstance().chatManager().addMessageListener(msgListener);

        conversationListFragment = new EaseConversationListFragment();

        conversationListFragment.setConversationListItemClickListener(new EaseConversationListFragment.EaseConversationListItemClickListener() {

            @Override
            public void onListItemClicked(EMConversation conversation) {
                boolean canTalk = true;
                String name = "";
                if (users != null) {
                    for (UserInfoBean user : users) {
                        if (conversation.getUserName().contains(user.getTel())) {
                            name = user.getName();
                            if (user.getIsBinding().equals("1")) {
                                canTalk = true;
                            } else {
                                canTalk = false;
                            }
                            break;
                        }
                    }
                }
                if (canTalk) {
//                    try {
                    Intent iChat = new Intent(MessageMainActivity.this, ChatFragmentActivity.class);
                    iChat.putExtra(EaseConstant.EXTRA_USER_ID, conversation.getUserName());
                    iChat.putExtra("name", name);
                    startActivity(iChat);
//                        startActivity(new Intent(MessageMainActivity.this, ChatFragmentActivity.class).putExtra(EaseConstant.EXTRA_USER_ID, conversation.getUserName()).putExtra("name", conversation.getLastMessage().getStringAttribute("name")));
//                    } catch (HyphenateException e) {
//                        Log.e("easechat", e.toString());
//                    }
                } else {
                    toastMsg(R.string.nobindingnotalk);
                }
            }
        });
        conversationListFragment.setUserInfoListener(new EaseConversationListFragment.getUserInfoListener() {
            @Override
            public void getUserInfo(List<String> tels) {
                YiJiaHuNetWorkUtils.getUserInfo(tels, handler);
            }
        });

        getSupportFragmentManager().beginTransaction().add(R.id.ll_messageMain_users, conversationListFragment).commit();
        conversationListFragment.refresh();
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean chatnew = false;
        List<EMConversation> conversations = conversationListFragment.getConversations();
        for (EMConversation conversation : conversations) {
            if (conversation.getUnreadMsgCount() > 0) {
                chatnew = true;
                break;
            }
        }
        if (chatnew) {
            YjhApplication.msg_chat = true;
        } else {
            YjhApplication.msg_chat = false;
        }

        if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_nurse)) {
            if (YjhApplication.msg_monitor) {
                iv_monitorp.setVisibility(View.VISIBLE);
            } else {
                iv_monitorp.setVisibility(View.INVISIBLE);
            }
            if (YjhApplication.msg_assessNurse) {
                iv_assessp.setVisibility(View.VISIBLE);
            } else {
                iv_assessp.setVisibility(View.INVISIBLE);
            }
            if (YjhApplication.msg_system) {
                iv_systemp.setVisibility(View.VISIBLE);
            } else {
                iv_systemp.setVisibility(View.INVISIBLE);
            }
        }

        YiJiaHuNetWorkUtils.checkNurseNewMsg(new IResponseNewMsgInfoListener() {
            @Override
            public void responseInfo(Object object) {
                int num=0;
                if (object!=null){
                    UserMsgBean nurseMsgBean = (UserMsgBean) object;
                    num =nurseMsgBean.getAssessPatient()+nurseMsgBean.getEvalution()+nurseMsgBean.getSystem();
                    if (nurseMsgBean.getAssessPatient()>0) {
                        iv_assessp.setVisibility(View.VISIBLE);
                    } else {
                        iv_assessp.setVisibility(View.INVISIBLE);
                    }
                    if (nurseMsgBean.getEvalution()>0) {
                        iv_evalutionp.setVisibility(View.VISIBLE);
                    } else {
                        iv_evalutionp.setVisibility(View.INVISIBLE);
                    }
//                    if (nurseMsgBean.getSystem()>0) {
//                        iv_systemp.setVisibility(View.VISIBLE);
//                    } else {
//                        iv_systemp.setVisibility(View.INVISIBLE);
//                    }
                }
                num +=YjhApplication.getInstance().getMsgNum();
                BadgeUtil.setBadgeCount(MessageMainActivity.this,num);
            }
        });

        if ((loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) &&
                (YjhApplication.msg_assessPatient || YjhApplication.msg_system || YjhApplication.msg_chat || YjhApplication.msg_evalution)) {
            YjhApplication.msg_new = true;
        } else if ((loginInfo.getUserStyle().equals(YjhApplication.userstyle_nurse)) && (YjhApplication.msg_monitor || YjhApplication.msg_assessNurse
                || YjhApplication.msg_system || YjhApplication.msg_chat)) {
            YjhApplication.msg_new = true;
        } else {
            YjhApplication.msg_new = false;
        }

        if (TextUtils.isEmpty(SharedPreferenceUtil.getSysMsg(this))) {
            iv_systemp.setVisibility(View.INVISIBLE);
        } else {
            iv_systemp.setVisibility(View.VISIBLE);
        }

    }

    private void initListener() {
//appbar是否显示 的监听，用来控制列表是否可以刷新
//        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
//            @Override
//            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//                if (verticalOffset >= 0) {
//                    recycleView.setCanRefresh(true);
//                    recycleView.setCanLoadMore(false);
//                } else if (verticalOffset <= -appBarLayout.getMeasuredHeight()) {
//                    recycleView.setCanRefresh(false);
//                    recycleView.setCanLoadMore(true);
//                } else {
//                    recycleView.setCanRefresh(false);
//                    recycleView.setCanLoadMore(false);
//                }
//            }
//        });
    }

    private void initData() {
//        msgs = new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            MessageBean bean = new MessageBean();
//            bean.setName("name" + i);
//            bean.setDate("201" + i);
//            bean.setHead("2342");
//            bean.setLastestMessage("message:" + i);
//            bean.setNum("" + i);
//            msgs.add(bean);
//        }
//
//        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
//        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//        recycleView.setLayoutManager(mLayoutManager);
//        refreshLayout.setOnRefreshListener(this);
//
//        adapter = new MsgMainAdapter(mContext, screenWidth, msgs);
//        recycleView.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.ll_messagemain_allcontacts:
                StringUtil.zhugeTrack(mContext, "所有联系人", "所有联系人点击数");

                Intent iContacts = new Intent(mContext, ContactListActivity.class);
                startActivity(iContacts);
                break;
            case R.id.ll_messagemain_monitor:
                StringUtil.zhugeTrack(mContext, "监测提醒", "监测提醒点击数");

                YjhApplication.msg_monitor = false;
                setMsg();
                Intent iM = new Intent(mContext, MonitorInfoActivity.class);
                startActivity(iM);
                break;
            case R.id.ll_messagemain_assess:
                StringUtil.zhugeTrack(mContext, "评估提醒", "评估提醒点击数");

                if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_nurse)) {
                    YjhApplication.msg_assessNurse = false;
                    setMsg();
                    Intent iA = new Intent(mContext, EvaluateInfoActivity.class);//消息，评估提醒(医护端)
                    startActivity(iA);
                } else if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) {
                    YjhApplication.msg_assessPatient = false;
                    setMsg();
                    Intent iA = new Intent(mContext, EvaluateInfoPActivity.class);//消息，评估提醒(患者端)
                    startActivity(iA);
                }
                break;
            case R.id.ll_messagemain_evalution:
                StringUtil.zhugeTrack(mContext, "医生评价", "医生评价点击数");

                YjhApplication.msg_evalution = false;
                setMsg();
                Intent iEvalution = new Intent(mContext, DoctorEvalutionActivity.class);
                startActivity(iEvalution);
                break;
            case R.id.ll_messagemain_system:
                StringUtil.zhugeTrack(mContext, "系统消息", "系统消息点击数");
                SharedPreferenceUtil.setSysMsg(this,"");
                YjhApplication.msg_system = false;
                Intent iS = new Intent(mContext, SystemInfoActivity.class);
                startActivity(iS);
                break;
        }
    }

    private void setMsg() {
        if ((loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) &&
                (YjhApplication.msg_assessPatient || YjhApplication.msg_system || YjhApplication.msg_chat || YjhApplication.msg_evalution)) {
            YjhApplication.msg_new = true;
        } else if ((loginInfo.getUserStyle().equals(YjhApplication.userstyle_nurse)) && (YjhApplication.msg_monitor || YjhApplication.msg_assessNurse
                || YjhApplication.msg_system || YjhApplication.msg_chat)) {
            YjhApplication.msg_new = true;
        } else {
            YjhApplication.msg_new = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
    }

    public static MessageMainActivity getInstance() {
        return messageMainActivity;
    }

    public void jpushNew() {
        if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_nurse)) {
            if (YjhApplication.msg_monitor) {
                iv_monitorp.setVisibility(View.VISIBLE);
            } else {
                iv_monitorp.setVisibility(View.INVISIBLE);
            }
            if (YjhApplication.msg_assessNurse) {
                iv_assessp.setVisibility(View.VISIBLE);
            } else {
                iv_assessp.setVisibility(View.INVISIBLE);
            }
            if (YjhApplication.msg_system) {
                iv_systemp.setVisibility(View.VISIBLE);
            } else {
                iv_systemp.setVisibility(View.INVISIBLE);
            }
        }
        if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) {
            if (YjhApplication.msg_assessPatient) {
                iv_assessp.setVisibility(View.VISIBLE);
            } else {
                iv_assessp.setVisibility(View.INVISIBLE);
            }
            if (YjhApplication.msg_evalution) {
                iv_evalutionp.setVisibility(View.VISIBLE);
            } else {
                iv_evalutionp.setVisibility(View.INVISIBLE);
            }
            if (YjhApplication.msg_system) {
                iv_systemp.setVisibility(View.VISIBLE);
            } else {
                iv_systemp.setVisibility(View.INVISIBLE);
            }
        }
    }

}
